package com.jacobson.core.widget.rv

import android.annotation.SuppressLint
import android.content.Context
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import com.jacobson.core.framework.delegation.WeakRef


/**
 * ================================================
 *
 *  @author Wucz on 2018-09-04 15:51
 * ================================================
 */

class OnBlankPlaceClickListener(
        context: Context,
        private val listener: () -> Unit
) : View.OnTouchListener {
    private val context by WeakRef {
        context.applicationContext ?: context
    }
    private var downX = 0f
    private var downY = 0f
    private var downTime = 0L

    @SuppressLint("ClickableViewAccessibility")
    override fun onTouch(v: View, event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_DOWN) {
            downX = event.x
            downY = event.y
            downTime = System.currentTimeMillis()
        } else if (isActionClickUp(event)) {
            listener.invoke()
            return true
        }
        return false
    }

    private fun isActionClickUp(e: MotionEvent): Boolean {
        val configuration = ViewConfiguration.get(context)
        return e.action == MotionEvent.ACTION_UP &&
                System.currentTimeMillis() - downTime <= ViewConfiguration.getTapTimeout() &&
                e.x - downX <= configuration.scaledTouchSlop &&
                e.y - downY <= configuration.scaledTouchSlop
    }
}